<template>
  <el-dialog :visible="visible" width="60%" top="1%" @close="resetForm">
    <search-form
      v-model="formOption.data"
      :form-option="formOption"
      :show-btn="true"
      :btn-list="btnList"
      label-width="90px"
    />
    <PageTable :loading="loading" :columns="columns" :data="dataSource" />

    <div class="footer-button">
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getGoodsList"
      />

      <div>
        <el-button @click="resetForm"> 取消 </el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { GOODS_SATAUS_NAME } from '@/enum/goods'
export default {
  name: 'GoodsPopup',
  props: {
    value: {
      type: Object,
      default: () => {}
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      // 选择商品id
      rowId: '',
      formOption: {
        // 搜索表单
        data: {
          name: '',
          categoryOneId: '',
          categoryTwoId: ''
        },
        items: [
          {
            type: 'input',
            label: '商品名称',
            value: 'name',
            style: {
              width: '150px'
            }
          },
          {
            type: 'select',
            label: '商品分类',
            value: 'categoryOneId',
            selectList: []
          },
          {
            type: 'select',
            label: '',
            labelWidth: '0',
            value: 'categoryTwoId',
            selectList: []
          }
        ]
      },
      btnList: [
        {
          type: 'primary',
          label: '搜索',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getGoodsList()
          }
        }
      ],
      // 源数据
      dataSource: [],
      total: 0,
      // 分页配置
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      columns: [
        {
          label: '商品',
          render: (h, { row }) => {
            return (
              <div style={'display: flex;align-items: center;'}>
                <img src={row.mainGraph} style={'width: 60px;height: 60px;'} />
                <span class="pl-10">{row.name}</span>
              </div>
            )
          }
        },
        {
          prop: 'minPrice',
          label: '价格'
        },
        {
          prop: 'validStockQuantity',
          label: '库存'
        },
        {
          label: '上架状态',
          render: (h, { row }) => {
            const styleObj = {
              1: '#333',
              2: '#409eff',
              3: '#fc4541'
            }
            return (
              <span style={`color: ${styleObj[row.sellType]}`}>
                {GOODS_SATAUS_NAME[row.sellType]}
              </span>
            )
          }
        },
        {
          label: '操作',
          render: (h, { row }) => {
            return <el-checkbox value={row.checked} onChange={() => this.checkedChange(row)} />
          }
        }
      ]
    }
  },
  computed: {
    // 控制弹窗显示
    visible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val)
      }
    }
  },
  created() {
    this.rowId = this.value?.id
    // 获取商品列表
    this.getGoodsList()
    // 获取一级分类
    this.getClassifyList()
  },
  mounted() {},
  watch: {
    // 监听一级分类设置
    'formOption.data.categoryOneId'(newValue, oldValue) {
      this.formOption.data.categoryTwoId = ''
      this.formOption.items = this.formOption.items.map(el => {
        const newEl = this.$lodash.cloneDeep(el)
        if (newEl.value === 'categoryTwoId') {
          newEl.selectList = []
        }
        return newEl
      })
      if (newValue) {
        this.getClassifyList(newValue, 'categoryTwoId')
      }
    }
  },
  methods: {
    // 获取商品列表
    async getGoodsList() {
      try {
        // 参数整理
        const pramas = {
          ...this.listQuery,
          ...this.formOption.data
        }
        // 发送请求
        const {
          data: { records, total }
        } = await this.$http.goods.newcomer.getCopyPageList(pramas)
        this.dataSource = records.map(item => {
          if (item.id == this.value?.id) {
            return { ...item, checked: true }
          }
          return { ...item, checked: false }
        })
        this.total = total
        this.loading = false
      } catch (error) {
        console.log('getGoodsList', error)
      }
    },

    // 获取分类列表
    async getClassifyList(parentId = 0, key = 'categoryOneId') {
      try {
        const { data } = await this.$http.goods.classify.getByParentId({ params: { parentId } })
        this.formOption.items = this.formOption.items.map(el => {
          const newEl = this.$lodash.cloneDeep(el)
          if (newEl.value === key) {
            newEl.selectList = data.map(el => ({ ...el, label: el.name, value: el.id }))
          }
          return newEl
        })
      } catch (error) {
        console.log('getClassifyList', error)
      }
    },

    // 选中商品
    checkedChange(val) {
      this.dataSource = this.dataSource.map(item => {
        if (val.id === item.id) {
          return { ...item, checked: true }
        }
        return { ...item, checked: false }
      })
      this.rowId = val.id
    },

    // 确定
    submitForm() {
      if (!this.rowId) {
        this.$message.error('请选择商品！')
        return
      }
      const { id, name, mainGraph } = this.dataSource?.find(item => item.id === this.rowId)
      // 传递
      this.$emit('input', { id, name, mainGraph })
      this.rowId = ''
      this.visible = false
    },

    resetForm() {
      this.visible = false
      this.rowId = ''
      if (!this.value) {
        this.$emit('input', {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer-button {
  @include flex();
}
</style>
